package tingyugetc;

import me.tingyugetc.crawler.fetcher.PageFetcher;
import me.tingyugetc.crawler.fetcher.authentication.FormLogin;
import me.tingyugetc.crawler.fetcher.entity.MethodType;
import org.apache.http.HttpEntity;
import org.apache.http.cookie.Cookie;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

    private PageFetcher pageFetcher;

    public Main() {
        this.pageFetcher = new PageFetcher();
    }

    private String getHtml(String url) {
        String result = "";
        try {
            result = this.pageFetcher.fetcher(url);

        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return  result;
    }

    private String login(String url) {
        Map<String, String> formField = new HashMap<String, String>();
        formField.put("username", "admin");
        formField.put("password", "123456");

        String response = "";
        FormLogin formLogin = new FormLogin(url, MethodType.POST, formField);
        try {
            HttpEntity result = this.pageFetcher.doFormLogin(formLogin);

//            List<Cookie> cookies = this.pageFetcher.getCookieStore().getCookies();
//            if (cookies.isEmpty()) {
//                System.out.println("None");
//            } else {
//                for (Cookie cookie : cookies) {
//                    System.out.println("- " + cookie.toString());
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    public static void main(String[] args) {
//        String url = "http://139.196.107.39/index.php?s=/Home/Article/index/category/teacher";

        String url = "http://139.196.107.39/admin.php?s=/Public/login";
        Main main = new Main();

        main.getHtml(url);
        main.login(url);

        String indexUrl = "http://139.196.107.39/admin.php?s=/Index/index";
        String html = main.getHtml(indexUrl);
        System.out.println(html);
//        System.out.println(HtmlParser.regexParse(html, "src=\"(.*?)\""));

    }
}
